#!/bin/bash

DefaultOldEncoding="GBK"
DefaultNewEncoding="UTF-8"

if [ "$#" != "1" ] && [ "$#" != "3" ]; then
    echo "Usage:"
    echo "    $0 DirectoryName"
    echo "    (It Can Mv All files $DefaultOldEncoding to $DefaultNewEncoding)"
    echo "    $0 DirectoryName OldEncoding to NewEncoding"
    echo "    (It Can Mv All files OldEncoding to NewEncoding)"
    exit -1
fi

tmpdir="./utf-8/"
# mkdir $tmpdir && cd $tmpdir
if [ "$#" == "3" ]; then
    DefaultOldEncoding="$2"
    DefaultNewEncoding="$3"
fi

dirs=$(find $1 -type d)
files=$(find $1 -type f)

for dir in $dirs
do
    mkdir -p $tmpdir"$dir"
    # echo $dir
done

for file in $files
do
    iconv -f $DefaultOldEncoding -t $DefaultNewEncoding $file > $tmpdir"$file"
    if [ "$?" != "0" ]; then
        rm -rf $tmpdir"$file"
    fi
done

cp -r $tmpdir/* .
rm -rf $tmpdir

exit 0
